import React, { Component, useEffect, useState, useRef } from "react";
import "../style/style.less";
import { Avatar, Space, Form, Input, Button } from "antd";
import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from "react-sortable-hoc";
import {
  MenuOutlined,
  EditOutlined,
  SettingOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import TheButton from "@/components/TheButton";
import arrayMove from "array-move";
import TheDialog from "@/components/TheDialog";
import TheTable from "@/components/TheTable";
import TheImage from "@/components/TheImage";
import { filtering } from "@/utils/regexp";
import { apiGetShufflingList, apiGetShufflingSort, apiGetShufflingAdd, apiGetShufflingEdit, apiGetShufflingDel } from '@/request/configuration'
import Editor from "../../component/editor";
import _ from 'lodash'
import _connect from '@/_connect'
const DragHandler = SortableHandle(() => (
  <TheButton haspermi={['service:category:update']}  ><MenuOutlined style={{ cursor: "grab", color: "#999" }} /></TheButton>

));

const SortableItem = SortableElement(
  ({ value, onEdit, onDelete }) => {
    return (
      <div className={"category-card"}>
        {value.serviceClassifySort !== "1" && <DragHandler />}
        <div style={{ display: "flex", justifyContent: "flex-end" }}>
          <EditOutlined
            onClick={() => onEdit(value)}
            style={{ cursor: "pointer", position: "unset", marginRight: 15 }}
          />
          {value.serviceClassifySort !== "1" && <DeleteOutlined
            onClick={() => onDelete(value)}
            style={{ cursor: "pointer", position: "unset" }}
          />}
        </div>
        <div className={"category-content"}>
          <Avatar
            size={80}
            src={value.configCarouselFilez}
          />
          <span>{value.configCarouselTitle}</span>
        </div>
      </div>
    );
  }
);

const SortableList = SortableContainer(({ children }) => {
  return <>{children}</>;
});


class Category extends Component {
  state = {
    dataSource: [],
    mallData: [],
    title: "",
    dialogStatus: false,
    editValue: null,
    editMode: false,
    editType: "",
    btnLoading: false,
    classifyJson: "",
    len: 0,
    tableIndex: 0,
    columns: [
      {
        title: "序号",
        dataIndex: "configCarouselSort",
        key: "configCarouselSort",
        // render: (text, record, index) => {
        //   return index+1;
        // }
      },
      {
        title: "标题",
        dataIndex: "configCarouselTitle",
        key: "configCarouselTitle",
      },
      {
        title: "图片",
        dataIndex: "configCarouselFilez",
        key: "configCarouselFilez",
        render: (text, record, index) => {
          if (text) {
            let arr = text.split(',')
            return <Space>
              {
                arr.map(v => {
                  return <TheImage src={v} width={80} height={80} />
                })
              }
            </Space>
          }
        }
      },
      {
        title: "操作",
        dataIndex: "serviceShowFile",
        key: "serviceShowFile",
        fixed: 'right',
        render: (text, render, index) => {
          return <div>
            <TheButton onClick={() => this.onEdit(render, index)}>编辑</TheButton>
            <TheButton onClick={() => this.onDelete(render, index)}>删除</TheButton>
          </div>
        }
      },
    ],
  };

  componentDidMount() {
    this.props.onChildEvent(this)
    // await this.getData()
    // this.onSortEnd({oldIndex:0,newIndex:0})
  }
  showData = (e) => {
    console.log(e)
    this.setState({
      dataSource: e
    })
  }
  getData = async () => {
    const response = await apiGetShufflingList({ configCarouselSite: '0' });
    if (response.code === 0) {
    }
  };
  onSortEnd = ({ oldIndex, newIndex }) => {
    console.log({ oldIndex, newIndex });
    this.setState(
      ({ dataSource }) => ({
        dataSource: arrayMove(dataSource, oldIndex, newIndex),
      }),
      () => {
        const dataSource = this.state.dataSource.map((v, i) => {
          delete v.createTime
          delete v.createUser
          delete v.updateTime
          delete v.updateUser
          return {
            ...v,
            configCarouselSort: i + 1,
          };
        });
        console.log(dataSource);
        const classifyJson = dataSource;
        this.setState({
          dataSource,
          classifyJson,
        }, async () => {
          // await apiGetShufflingSort({ configCarousels: this.state.classifyJson })
          // this.getData()
        });
      }
    );
  };
  onEdit = (value, index) => {
    // console.log(value)
    this.setState({
      dialogStatus: true,
      editValue: value,
      editType: "editor",
      title: '修改',
      tableIndex: index
    });
  };
  onDelete = (value, index) => {
    // console.log(value,index);
    React.$confirm({
      title: `您确定删除名称为${value.configCarouselTitle}的按钮吗？`,
      onOk: async () => {
        let { dataSource } = this.state
        dataSource.splice(index, 1)
        this.setState({
          dataSource: [...dataSource]
        })
        this.initData(dataSource)
      },
    });
  };
  onAdd = () => {
    this.setState({
      dialogStatus: true,
      editValue: null,
      editType: 'add',
      title: '新增'
    });
  }
  dialogCancel = () => {
    this.setState({
      title: "",
      dialogStatus: false,
      editValue: null,
      editType: ''
    });
  };
  onFinish = async (value) => {
    console.log("=====================onFinish==============================", value);
    const { editValue, } = this.state
    const keys = Object.keys(value);
    const { editType } = this.state
    // console.log(value)
    this.setState({
      btnLoading: true,
    });
    if (editType === 'add') {
      let { dataSource } = this.state
      dataSource.push(value)
      this.setState({
        dataSource: [...dataSource]
      }, () => {
        this.dialogCancel();
        React.$message({
          type: "info",
          content: "新增成功",
        });
        this.setState({
          btnLoading: false,
        });
        this.initData(dataSource)
      })
    } else {
      let { dataSource, tableIndex } = this.state
      dataSource[tableIndex] = value
      this.setState({
        dataSource: [...dataSource]
      }, () => {
        this.dialogCancel();
        React.$message({
          type: "info",
          content: "修改成功",
        });
        this.setState({
          btnLoading: false,
        });
        this.initData(dataSource)
      })
    }
  };
  initData = (data) => {
    this.props.refreshData(data)
  }
  render() {
    const {
      dataSource,
      editValue,
      dialogStatus,
      columns,
      editType,
      btnLoading,
      title
    } = this.state;
    return (
      <div >
        <div
          style={{
            display: "flex",
            justifyContent: "flex-start",
            marginBottom: 30,
          }}
        >
          {
            dataSource.length === 15 ? <TheButton disabled size={"middle"} type={"default"}>表格已满
            </TheButton> : <TheButton onClick={this.onAdd} size={"middle"} type={"default"}>
              新增</TheButton>
          }

        </div>
        <TheTable
          scroll={{ x: "max-content", y: '48vh' }}
          columns={columns}
          dataSource={dataSource}
        />
        <TheDialog
          visible={dialogStatus}
          title={title}
          width={800}
          handleCancel={this.dialogCancel}
          footer={null}
        >
          <Editor dialogCancel={this.dialogCancel} onFinish={this.onFinish} data={editValue}
            btnLoading={btnLoading}
            type={editType}
          />
        </TheDialog>
      </div>
    );
  }
}

export default _connect(Category);
